<template>
  <view v-if="visible">
    <view class="overlay" @click="closeDialog"></view>
    <view class="dialog">
      <view class="content">
        {{ messageTxt }}
        <slot></slot>
      </view>
    </view>
  </view>
</template>

<script>
import authority from './authority.js'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    messageTxt: {
      type: String,
      default: ''
    },
    confirmModalTxt: {
      type: String,
      default:
        '用于获取设备权限进行二维码、条形码扫描和图片识别,请打开手机相机、相册（存储）权限（点击确定后在权限中授权相机相册功能）'
    },
    type: {
      type: String,
      default: ''
    }
  },
  created () {
    this.permission()
  },
  methods: {
    async permission () {
      if (this.type === 'phone') {
        return
      }
      let CAMERA, READ_MEDIA_IMAGES, READ_EXTERNAL_STORAGE
      if (uni.getSystemInfoSync().platform === 'ios') {
        ;[CAMERA, READ_EXTERNAL_STORAGE] = await Promise.all([
          authority.judgeIosPermission('camera'),
          authority.judgeIosPermission('photoLibrary')
        ])
        let firstCamera = uni.getStorageSync('iosFirstCamera')
        if (!firstCamera) {
          uni.setStorageSync('iosFirstCamera', true)
          CAMERA = true
        }
        if (CAMERA || READ_EXTERNAL_STORAGE) {
          this.$emit('scanCoding', '')
        }
      } else {
        CAMERA = await authority.requestAndroidPermission('android.permission.CAMERA')
        READ_MEDIA_IMAGES = await authority.requestAndroidPermission(
          'android.permission.READ_MEDIA_IMAGES'
        )
        READ_EXTERNAL_STORAGE = await authority.requestAndroidPermission(
          'android.permission.READ_EXTERNAL_STORAGE'
        )
        if (
          (CAMERA === 1 && READ_MEDIA_IMAGES === 1 && READ_EXTERNAL_STORAGE === 1) ||
          (CAMERA === 1 && READ_MEDIA_IMAGES === 1) ||
          (CAMERA === 1 && READ_EXTERNAL_STORAGE === 1)
        ) {
          this.$emit('scanCoding', '')
        } else {
          authority.gotoAppPermissionSetting()
        }
      }
      if (CAMERA === 1 && READ_MEDIA_IMAGES === 1 && READ_EXTERNAL_STORAGE === 1) {
        this.closeDialog()
      }
    },
    // 关闭弹框方法
    closeDialog () {
      this.$emit('updateVisible', false)
    }
  }
}
</script>

<style>
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.dialog {
  position: fixed;
  top: 30%;
  left: 50%;
  width: 60%;
  transform: translate(-50%, -50%);
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  z-index: 1000;
}
</style>
